1844E - Great Grids - CodeForces Solution


2-sat constructive algorithms dfs and similar dsu graphs

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
using namespace std;

#define ll long long

const int MXN = 4005;
vector<pair<int, int>> adj[MXN];
int color[MXN], bad = 0;

int dfs(int u, int c) {
    if (color[u] != -1) {
        if (color[u] != c) bad = 1;
        return 0;
    }

    color[u] = c;

    for (auto p: adj[u]) dfs(p.first, c ^ p.second);

    return 0;
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    int t;
    cin >> t;

    while (t--) {
        int n, m, k;
        cin >> n >> m >> k;

        for (int i = 0; i < k; ++i) {
            int x1, y1, x2, y2;
            cin >> x1 >> y1 >> x2 >> y2;

            --x1, --x2, --y1, --y2;

            adj[min(x1, x2)].push_back({ n + min(y1, y2), (x1 + y1 != x2 + y2) });
            adj[n + min(y1, y2)].push_back({ min(x1, x2), (x1 + y1 != x2 + y2) });
        }

        fill(color, color+n+m, -1);
        bad = 0;

        for (int i = 0; i < n + m; ++i) {
            if (color[i] == -1) dfs(i, 0);
        }

        cout << (bad ? "NO\n" : "YES\n");

        for (int i = 0; i < n+m; ++i) adj[i].clear();
    }

    return 0;
}


Comments

Submit
0 Comments
More Questions

709A - Juicer
1358C - Celex Update
1466B - Last minute enhancements
450B - Jzzhu and Sequences
1582C - Grandma Capa Knits a Scarf
492A - Vanya and Cubes
217A - Ice Skating
270A - Fancy Fence
181A - Series of Crimes
1638A - Reverse
1654C - Alice and the Cake
369A - Valera and Plates
1626A - Equidistant Letters
977D - Divide by three multiply by two
1654B - Prefix Removals
1654A - Maximum Cake Tastiness
1649A - Game
139A - Petr and Book
1612A - Distance
520A - Pangram
124A - The number of positions
1041A - Heist
901A - Hashing Trees
1283A - Minutes Before the New Year
1654D - Potion Brewing Class
1107B - Digital root
25A - IQ test
785A - Anton and Polyhedrons
1542B - Plus and Multiply
306A - Candies